/**
 * OSAmI: Open Source Ambient Intelligence
 * Servlets running on the gateway, for displaying data from the sensor nodes.
 * Copyright (C) Jonathan Ferreira 2010 (internship in LCIS-INPG, for a demo in the FR part of the OSAMI project)
 * Contact: osami-general@osami-commons.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA
 */
package org.osami.gateway.display.internal;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Instantiate;
import org.apache.felix.ipojo.annotations.Invalidate;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.Validate;
import org.osami.gateway.identity.Identity;
import org.osami.gateway.identity.IdentityProvider;
import org.osami.gateway.sensor.data.SenseData;
import org.osami.gateway.storage.ISenseDataStorage;
import org.osgi.service.http.HttpContext;
import org.osgi.service.http.HttpService;
import org.osgi.service.http.NamespaceException;

@Component
@Instantiate
public class SensorViewServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Requires
    private ISenseDataStorage storage;

    @Requires
    private HttpContext context;

    @Requires
    private HttpService httpService;

    private final DateFormat df = new SimpleDateFormat("yyyy/MM/dd'&nbsp;&nbsp;'HH:mm:ss:SSS z");

    @Requires(optional = true)
    private IdentityProvider identityProvider;

    @Validate
    public void start() throws ServletException, NamespaceException {
        this.httpService.registerServlet(ServletPaths.SENSOR, this, null, this.context);
    }

    @Invalidate
    public void stop() {
        this.httpService.unregister(ServletPaths.SENSOR);
    }

    @Override
    synchronized public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String urlData = request.getRequestURI();
        String[] t = urlData.split(ServletPaths.SENSOR + "/");

        urlData = t[1];
        t = urlData.split("/");
        String nodeId = t[0];
        String urlType = "";
        String urlUnit = "";

        synchronized (this.storage) {
            for (SenseData sd : this.storage) {
                if (sd.getSenseId().equals(urlData)) {
                    urlType = sd.getType();
                    urlUnit = sd.getUnit();
                    break;
                }
            }
        }

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");
        out.println("<html lang=\"en\">");
        out.println("<head><title>Sensor Data: " + urlData + "</title>");
        out.println("<meta http-equiv=\"refresh\" content=\"7\">");
        out.println("<link href=\"/resource/css/designSensor.css\" rel=\"stylesheet\" type=\"text/css\" />");
        out.println("\t<script src=\"/resource/jquery.min.js\" type=\"text/javascript\"></script>");
        out.println("\t<script src=\"/resource/Highcharts/js/highcharts.js\" type=\"text/javascript\"></script>");
        out.println("\t<!--[if IE]>");
        out.println("\t\t<script src=\"/resource/Highcharts/js/excanvas.compiled.js\" type=\"text/javascript\"></script>");
        out.println("\t<![endif]-->");
        out.println("\t<script src=\"/resource/chart.js\" type=\"text/javascript\"></script>");
        out.println("</head>");
        out.println("<body>");

        String identityName = "";

        if (this.identityProvider != null) {
            final Identity identity = this.identityProvider.getBoundIdentity(nodeId);
            if (identity != null) {
                final String identityName2 = identity.getName();
                if (identityName2 != null && !identityName2.equals("")) {
                    identityName = identityName2;
                }
            }
        }

        if (!identityName.equals("")) {
            out.println("\t<h1>Sensor data history (charts) for " + identityName + "/" + urlType + "</h1>");
            out.println("\t<hr>");
            out.println("<input type=\"hidden\" id=\"nodeName\" value=\"" + identityName + "/" + urlType + "\" />");
        }
        else {
            out.println("\t<h1>Sensor data history (charts) for " + urlData + "</h1>");
            out.println("\t<hr>");
            out.println("<input type=\"hidden\" id=\"nodeName\" value=\"" + urlData + "\" />");
        }
        out.println("<input type=\"hidden\" id=\"urlData\" value=\"" + urlData + "\" />");
        out.println("<input type=\"hidden\" id=\"urlType\" value=\"" + urlType + "\" />");
        out.println("<input type=\"hidden\" id=\"urlUnit\" value=\"" + urlUnit + "\" />");

        out.println("\n\t<div id=\"chart-container-1\" style=\"width: 100%; height: 100%\"></div>");

        List<SenseData> filteredDatas = new ArrayList<SenseData>();

        synchronized (this.storage) {
            for (SenseData sd : this.storage) {
                if (sd.getSenseId().equals(urlData)) {
                    filteredDatas.add(sd);
                }
            }
        }

        out.println("<hr/>\n");
        out.println("<a href=\"" + ServletPaths.NODE + "/" + nodeId + "\">Go back to node page</a><br />");
        out.println("<a href=\"" + ServletPaths.SENSORS + "\">Go back to sensors page</a><br />");
        out.println("<a href=\"" + ServletPaths.INDEX + "\">Go back to main page</a>\n");
        out.println("<hr/>\n");

        if (!identityName.equals("")) {
            out.println("<br/><h1>Sensor data history (table) for " + identityName + "/" + urlType + "</h1><hr/>");
            printTable(identityName + "/" + urlType, out, filteredDatas);
        }
        else {
            out.println("<br/><h1>Sensor data history (table) for " + urlData + "</h1><hr/>");
            printTable(urlData, out, filteredDatas);
        }

        out.println("<hr/>\n");
        out.println("<a href=\"" + ServletPaths.NODE + "/" + nodeId + "\">Go back to node page</a><br />");
        out.println("<a href=\"" + ServletPaths.SENSORS + "\">Go back to sensors page</a><br />");
        out.println("<a href=\"" + ServletPaths.INDEX + "\">Go back to main page</a>");
        out.println("</body>");
        out.println("</html>");
        out.flush();
    }

    private void printTable(String title, PrintWriter writer, List<SenseData> datas) {
        writer.println("<br/><br/>");
        writer.println("<table>");

        writer.println("<caption>" + title + "</caption>");

        // Print table headers
        writer.println("<thead><tr>");
        writer.println("<th>Type</th>");
        writer.println("<th>Value</th>");
        writer.println("<th>Unit</th>");
        writer.println("<th>Time</th>");
        writer.println("</tr></thead>");

        // Print table body
        writer.println("<tbody>");

        for (SenseData data : datas) {
            writer.println("<tr>");
            writer.println("<td>" + data.getType() + "</td>");
            writer.println("<td>" + data.getValue() + "</td>");
            writer.println("<td>" + data.getUnit() + "</td>");

            Date date = new Date(data.getTimeStamp());
            StringBuffer sb = this.df.format(date, new StringBuffer(), new FieldPosition(DateFormat.FULL));
            writer.println("<td>" + sb.toString() + "</td>");

            writer.println("</tr>");
        }

        writer.println("</tbody>");
        writer.println("</table>");
    }
}
